﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using CameraViewer.Forms;
using CameraViewer.Model;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.XtraSplashScreen;
using log4net;


namespace CameraViewer
{
    class Program
    {
        public static bool FullScreen;
        public static bool CameraRelay;
        public static bool AutoConnectCameras;
        public static string RelayHostIpPort;
        private static readonly ILog logger = LogManager.GetLogger(typeof(Program));
        public static IniParser.IniData IniData;

        public static string WebServerIp;
        public static string conn;

        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;



            Boolean createdNew; //返回是否赋予了使用线程的互斥体初始所属权
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(Properties.Settings.Default.DefaultSkinName);

            IniData = new IniParser.FileIniDataParser().LoadFile("Config.ini");
            var ftp = "Ftp";
            FtpService.HostIp = IniData[ftp]["Server"];
            FtpService.UserName = IniData[ftp]["UserName"];
            FtpService.Password = IniData[ftp]["Password"];

            var db = "Database";
            var server = IniData[db]["Server"];
            var user = IniData[db]["UserName"];
            var pwd = IniData[db]["Password"];

            WebServerIp = IniData["Web"]["Server"];


            FullScreen = IniData["UI"]["FullScreen"] == "1";
            AutoConnectCameras = IniData["UI"]["AutoConnectCameras"] == "1";

            CameraRelay = IniData["RelayCamera"]["Enabled"] == "1";
            RelayHostIpPort = IniData["RelayCamera"]["Host"];

            System.Threading.Mutex instance = new System.Threading.Mutex(true, "ArresterSerialPort", out createdNew); //同步基元变量
            if (createdNew)
            {
                SplashScreenManager.ShowForm(typeof(SplashScreen1));
                SplashScreenManager.Default.SendCommand(SplashScreen1.SplashScreenCommand.SetStatusLabel, "开始连接数据库...");


                var cameras = new List<TOG_DEVICE>();

                try
                {
                    conn = OracleConnectionProvider.GetConnectionString(Program.IniData["Database"]["Server"], Program.IniData["Database"]["UserName"], Program.IniData["Database"]["Password"]);
                    Session.DefaultSession.ConnectionString = conn;
                    XpoDefault.GetDataLayer(conn, AutoCreateOption.None);

                    SplashScreenManager.Default.SendCommand(SplashScreen1.SplashScreenCommand.SetStatusLabel, "获取设备信息...");
                    cameras = Model.Repository.Instance.GetTogCameras().ToList();

                    SplashScreenManager.Default.SendCommand(SplashScreen1.SplashScreenCommand.SetStatusLabel, "初始化完毕!");

                }
                catch (Exception ex)
                {
                    MessageBox.Show("无法连接数据库，请检查系统配置并确保数据库服务器已经运行。\n\n错误信息如下：\n" + ex.Message,
                           "错误", MessageBoxButtons.OK);
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm(cameras));



                GC.KeepAlive(instance);
            }

        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private static void HandleException(Exception e)
        {
            LogException(e);
            ShowException(e);
        }

        private static void ShowException(System.Exception e)
        {
            MessageBox.Show(e.Message, "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private static void LogException(System.Exception e)
        {
            logger.Error("Error occurred", e);
        }
    }
}
